$(function () {
    // 是否登陆
    goLogin();
    // 菜单键切换
    var i = 0;
    $('.header_menu').click(function () {
        if (i == 0) {
            $('#bottom').removeClass('tab');
            i = 1;
        } else {
            $('#bottom').addClass('tab');
            i = 0;
        };
    });

    // FOOTER
    footerFn();

    function footerFn() {
        post({
            url: '/member/phone/blur',
            success: function (data) {
                $('.foo_infor_name').text(data);
            }
        });
        $('.foo_infor_exit').click(function () {
            $.post({
                url: SERVER_CONTEXT_PATH+'/logout',
                success:function(){
                    go('/index.html');
                }
            });
            // setTimeout(go('/index.html'), 300);
        });
        $('.foo_infor_up').click(function () {
            $('html,body').animate({
                scrollTop: '0px'
            }, 200);
        });
    };
});
// 订单按钮函数
function orderBtnFn() {
    // 删除订单
    $('.del_order').click(function () {
        var _this = $(this);
        $('.gat_alert>p').text('是否确定删除该订单？');
        // $('.gat_background').removeClass('tab');
        $('.gat_background').removeClass('tab');
        $('.gat_alert').addClass('animated slideInDown');
        var code = $(this).attr('name');
        $('.gat_alert_cancel').click(function () {
            $('.gat_background').addClass('tab');
        });
        $('.gat_alert_affirm').click(function () {
            post({
                url: '/member/order/' + code + '/submitForDelete',
                success: function () {
                    // window.location.reload();
                    $('.gat_background').addClass('tab');
                    _this.parent().parent().addClass('tab');
                }
            });
        });
    });
    // 确认订单
    $('.gat_order').click(function () {
        $('.gat_alert>p').text('请收到货后，再确认收货！');
        // $('.gat_background').removeClass('tab');
        $('.gat_background').removeClass('tab');
        $('.gat_alert').addClass('animated slideInDown');
        var code = $(this).attr('name');
        $('.gat_alert_cancel').click(function () {
            $('.gat_background').addClass('tab');
        });
        $('.gat_alert_affirm').click(function () {
            post({
                url: '/member/order/' + code + '/submitForConfirm',
                success: function () {
                    window.location.reload();
                }
            });
        });
    });
    // 订单支付
    /*$('.pay_order').click(function () {
        var code = $(this).attr('name');
        var amount = $(this).data("amount");
        post({
            url:"/order/removeWechat",
            success:function(data){
                setCookie("wait-code",code);
                setCookie("wait-amount",amount);
                go("/mobileorder/selectpaytype.html");
            }
        });
        //if(isWeiXin()){ //微信支付
        //    weiXinPay(code);
        //}else{  //支付宝支付
        //    go("/order/payFor?code=" + code);
        //}
    });*/
}

// 订单支付
$('section').delegate(".pay_order","click",function () {
    var code = $(this).attr('name');
    var amount = $(this).data("amount");
    post({
        url: "/order/removeWechat",
        success: function (data) {
            setCookie("pay-content","store"); //支付内容
            setCookie("wait-code", code);
            setCookie("wait-amount", amount);
            setCookie("step", "1");
            setCookie("productdetailgoback",encodeURIComponent(window.location.href));
            go("/mobileorder/selectpaytype.html");
        }
    });
});

function weiXinPay(orderCodes){
    post({
        url:"/order/weChatPayFor",
        data:{orderCodes:orderCodes},
        success: function (data) {
            _appId = data.appId;
            _timeStamp = data.timeStamp;
            _nonceStr = data.nonceStr;
            _paySign = data.paySign;
            _signType = data.signType;
            prepay_id = data.prepay_id;
            onBridgeReady(orderCodes);
        }
    });
}

function onBridgeReady(orderCodes){
    WeixinJSBridge.invoke(
        'getBrandWCPayRequest', {
            "appId":_appId,     //公众号名称，由商户传入
            "timeStamp":_timeStamp,         //时间戳，自1970年以来的秒数
            "nonceStr":_nonceStr, //随机串
            "package":prepay_id,
            "signType":_signType,         //微信签名方式：
            "paySign":_paySign //微信签名
        },
        function(res){
            if(res.err_msg == "get_brand_wcpay_request:ok" ) {
                post({
                    url:"/weChat/success",
                    data:{
                        orderCodes:orderCodes
                    },
                    success:function(data){
                        go("/member/myorders/allorder.html");
                    }
                });
            }else{
                go("/member/myorders/obligation.html");
            }
        }
    );
}

function isWeiXin(){
    var ua = window.navigator.userAgent.toLowerCase();
    if(ua.match(/MicroMessenger/i) == 'micromessenger'){
        return true;
    }else{
        return false;
    }
}

// 交易关闭
function orderListFnA(listData, pageNum) {
    if(listData["shippingFee"] == null || listData["shippingFee"] ==''){
        listData["shippingFee"] = 0;
    };
    $('section').append(
        '<aside><div class="aside_top"><p class="orderNum">订单编号：<span>' + listData["code"] + '</span></p>' +
        '<p class="orderState">' + listData["status"]["text"] + '</p></div><div class="' + listData["code"] + '"></div>' +
        '<div class="aside_btm"><p class="aside_btm_text">共<span>' + listData["productNum"] + '</span>件商品，实付¥<span>' + returnFloat(listData["orderAmount"]) + '</span>' +
        '<span class="aside_btm_text_fei">（含运费¥<span>' + returnFloat(listData["shippingFee"]) + '</span>）</span>' +
        '</p></div></aside>'
        // '</p><div name="' + listData["code"] + '" class="del_order">删除订单</div></div></aside>'
    );
    orderListDetailsAFn(listData, listData["code"], pageNum);
};
// 待付款
function orderListFnB(listData, pageNum) {
    if(listData["shippingFee"] == null || listData["shippingFee"] ==''){
        listData["shippingFee"] = 0;
    };
    $('section').append(
        '<aside><div class="aside_top"><p class="orderNum">订单编号：<span>' + listData["code"] + '</span></p>' +
        '<p class="orderState">' + listData["status"]["text"] + '</p></div><div class="' + listData["code"] + '"></div>' +
        '<div class="aside_btm"><p class="aside_btm_text">共<span>' + listData["productNum"] + '</span>件商品，实付¥<span>' + returnFloat(listData["orderAmount"]) + '</span>' +
        '<span class="aside_btm_text_fei">（含运费¥<span>' + returnFloat(listData["shippingFee"]) + '</span>）</span>' +
        '</p><div data-amount="'+listData["orderAmount"]+'" name="' + listData["code"] + '" class="pay_order">订单支付</div><div name="' + listData["code"] + '" class="del_order">删除订单</div></div></aside>'
    );
    orderListDetailsBFn(listData, listData["code"], pageNum);
};
// 待收货
function orderListFnC(listData, pageNum) {
    if(listData["shippingFee"] == null || listData["shippingFee"] ==''){
        listData["shippingFee"] = 0;
    };
    var _items = listData.items;
    var f= true;
    var html_shou = '';
    for(var m in _items){
        if(_items[m].orderStatusDTO.status == 'WAIT_SEND'||_items[m].orderStatusDTO.status == 'WAIT_DELIVERY'){
            f=false;
        }
    }
    if (f == false) {
        html_shou = '<div name="' + listData["code"] + '" class="gat_order">确认收货</div>'
    }else{
        html_shou = ''
    };
    
    $('section').append(
        '<aside><div class="aside_top"><p class="orderNum">订单编号：<span>' + listData["code"] + '</span></p>' +
        '<p class="orderState">' + listData["status"]["text"] + '</p></div><div class="' + listData["code"] + '"></div>' +
        '<div class="aside_btm"><p class="aside_btm_text">共<span>' + listData["productNum"] + '</span>件商品，实付¥<span>' + returnFloat(listData["orderAmount"]) + '</span>' +
        '<span class="aside_btm_text_fei">（含运费¥<span>' + returnFloat(listData["shippingFee"]) + '</span>）</span>' +
        '</p>'+html_shou+'</div></aside>'
    );
    orderListDetailsAFn(listData, listData["code"], pageNum);
};
// 交易成功
function orderListFnD(listData, pageNum) {
    console.log(listData)
    if(listData["shippingFee"] == null || listData["shippingFee"] ==''){
        listData["shippingFee"] = 0;
    };
    $('section').append(
        '<aside><div class="aside_top"><p class="orderNum">订单编号：<span>' + listData["code"] + '</span></p>' +
        '<p class="orderState">' + listData["status"]["text"] + '</p></div><div class="' + listData["code"] + '"></div>' +
        '<div class="aside_btm"><p class="aside_btm_text">共<span>' + listData["productNum"] + '</span>件商品，实付¥<span>' + returnFloat(listData["orderAmount"]) + '</span>' +
        '<span class="aside_btm_text_fei">（含运费¥<span>' + returnFloat(listData["shippingFee"]) + '</span>）</span>' +
        '</p></div></aside>'
        // '</p><div name="' + listData["code"] + '" class="del_order">删除订单</div></div></aside>'
    );
    orderListDetailsAFn(listData, listData["code"], pageNum);
};
//待评论
function orderListFnF(listData, pageNum){
     console.log(listData)
    if(listData["shippingFee"] == null || listData["shippingFee"] ==''){
        listData["shippingFee"] = 0;
    };
    $('section').append(
        '<aside><div class="aside_top"><p class="orderNum">订单编号：<span>' + listData["code"] + '</span></p>' +
        '<p class="orderState">' + listData["status"]["text"] + '</p></div><div class="' + listData["code"] + '"></div>' +
        '<div class="aside_btm"><p class="aside_btm_text">共<span>' + listData["productNum"] + '</span>件商品，实付¥<span>' + returnFloat(listData["orderAmount"]) + '</span>' +
        '<span class="aside_btm_text_fei">（含运费¥<span>' + returnFloat(listData["shippingFee"]) + '</span>）</span>' +
        '</p></div></aside>'
        // +'</p><div name="' + listData["code"] + '" class="del_order">评论</div></div></aside>'
    );
    orderListDetailsAFn(listData, listData["code"], pageNum);
}
// 订单内容A
function orderListDetailsAFn(listData, dataDom, pageNum) {
    var orderList = {
        status: null,
        page: {
            "pageNo": pageNum,
            "pageSize": "5",
            "sorts": [{
                "order": "DESC",
                "property": "createTime"
            }]
        }
    };
    post({
        url: '/member/order/list',
        data: orderList,
        success: function (data) {
            var list = data.list;
            for (var j = 0; j < listData["items"].length; j++) {
                // console.log(listData["items"][j]);
                $('.' + dataDom + '').append(
                    '<div class="aside_center">' +
                    '<a href="../orderdetail/orderdetail.html#' + listData["code"] + '"><img class="aside_center_pic" src="' + SERVER_CONTEXT_PATH + '/load/picture/' + listData["items"][j]["productUrl"] + '" alt="">' +
                    '<div class="aside_center_text"><p>' + listData["items"][j]["productName"] + '</p><p class="_slide">' + listData["items"][j]["productRemark"] + '</p><div>' +
                    '<p class="aside_center_text_price">￥<span>' + returnFloat(listData["items"][j]["price"]) + '</span></p><p class="aside_center_text_num">×<span>' + listData["items"][j]["num"] + '</span></p>' +
                    '</div><span class="order_' + listData["items"][j]["id"] + '"></span></div></a></div>'
                );
                for (var k = 0; k < listData["items"][j]["specifications"].length; k++) {
                    $('.order_' + listData["items"][j]["id"] + '').append('' + listData["items"][j]["specifications"][k]["specValue"] + '&nbsp;&nbsp;&nbsp;&nbsp')
                };
            };
        }
    })
};
// 订单内容B
function orderListDetailsBFn(listData, dataDom, pageNum) {
    var orderList = {
        status: null,
        page: {
            "pageNo": pageNum,
            "pageSize": "5",
            "sorts": [{
                "order": "DESC",
                "property": "createTime"
            }]
        }
    };
    post({
        url: '/member/order/list',
        data: orderList,
        success: function (data) {
            var list = data.list;
            for (var j = 0; j < listData['items'].length; j++) {
                var time_creat = new Date(listData['createTime']);
                var time_deadline = new Date();
                var time = parseInt(((time_creat - time_deadline) / 60000) + 30);
                var timeD = '请在' + time + '分钟内支付';

                // 当时间小于零时，关闭订单
                if(time <= 0){
                    post({
                        url:'order/'+listData['code']+'/getFreezeInventoryClearer',
                        success:function(){
                        window.location.reload();
                        }
                    });
                };
                $('.' + dataDom + '').append(
                    '<div class="aside_center">' +
                    '<a href="../orderdetail/orderdetail.html#' + listData["code"] + '"><img class="aside_center_pic" src="' + SERVER_CONTEXT_PATH + '/load/picture/' + listData["items"][j]["productUrl"] + '" alt="">' +
                    '<div class="aside_center_text"><p>' + listData["items"][j]["productName"] + '</p><p class="_slide">' + listData["items"][j]["productRemark"] + '</p><div>' +
                    '<p class="aside_center_text_price">￥<span>' + returnFloat(listData["items"][j]["price"]) + '</span></p><p class="aside_center_text_num">×<span>' + listData["items"][j]["num"] + '</span></p>' +
                    '</div><span class="order_' + listData["items"][j]["id"] + '"></span></div>' +
                    '<div class="aside_time"><p>' + timeD + '</p></div></a></div>'
                );
                for (var k = 0; k < listData["items"][j]["specifications"].length; k++) {
                    $('.order_' + listData["items"][j]["id"] + '').append('' + listData["items"][j]["specifications"][k]["specValue"] + '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;')
                };
            };
        }
    })
};

$('section').delegate('.aside_center>a','click',function(){
    localStorage.setItem('orderUrl',window.location.href)
})